<template>
  <div class="home">
    <div class="featured-section" v-loading="loading.tjLoad">
      <!-- 轮播图区域 -->
      <el-carousel
          class="featured-carousel"
          height="530px"
          indicator-position="outside"
      >
        <el-carousel-item
            v-for="item in firstFourItems"
            :key="item.id"
            class="carousel-item"
        >
          <article
              class="carousel-card"
              role="article"
              @click="toArticle(item.id)"
          >
            <img
                :src="item.pic"
                :alt="`文章封面图：${item.title}`"
                class="carousel-image"
                loading="lazy"
            />
            <div class="carousel-content">
              <el-tag
                  type="success"
                  class="article-tag"
              >
                {{ showDictUtil(item.articleType, dict) }}
              </el-tag>
              <h2 class="article-title">
                {{ item.title }}
              </h2>
              <div class="article-meta">
                <time :datetime="item.createTime">
                  {{ parseTime(item.createTime, '{y}-{m}-{d}') }}
                </time>
                <span class="author">{{ item.user.nickName }}</span>
              </div>
            </div>
          </article>
        </el-carousel-item>
      </el-carousel>

      <!-- 右侧推荐文章列表 -->
      <ul class="recommend-list">
        <li
            v-for="item in remainingItems"
            :key="item.id"
            class="recommend-card"
        >
          <article
              class="card-article"
              role="article"
              @click="toArticle(item.id)"
          >
            <img
                :src="item.pic"
                :alt="`推荐文章封面：${item.title}`"
                class="card-image"
                loading="lazy"
            />
            <div class="card-content">
              <el-tooltip
                  :content="item.title"
                  placement="top"
                  :disabled="!isTitleOverflow(item.title)"
              >
                <h3 class="card-title">
                  {{ item.title }}
                </h3>
              </el-tooltip>
              <div class="card-meta">
                <el-tag
                    type="info"
                    size="small"
                    class="type-tag"
                >
                  {{ showDictUtil(item.articleType, dict) }}
                </el-tag>
                <div class="meta-info">
                  <time
                      :datetime="item.createTime"
                      class="create-time"
                  >
                    {{ parseTime(item.createTime, '{y}-{m}-{d}') }}
                  </time>
                  <span class="author">{{ item.user.nickName }}</span>
                </div>
              </div>
            </div>
          </article>
        </li>
      </ul>
    </div>
    <div class="sx" v-loading="loading.sxLoad">
      <div class="sx-but">
        <el-button-group>
          <el-button @click="selectedBut({value:''},'')" style="border-radius: 2px">全部</el-button>
          <el-button
              :class="{ 'is-active': activeBut === index }"
              v-for="(item,index) in buts"
              @click="selectedBut(item,index)"
              style="margin-left: 10px;border-radius: 2px"
          >
            {{ item.label }}
          </el-button>
        </el-button-group>
      </div>
      <div class="page">
        <el-pagination
            style="margin-right: 20px"
            v-model:current-page="page.currentPage"
            v-model:page-size="page.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :size="'default'"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

    </div>

    <div class="cards" v-loading="loading.cardsLoad">
      <div class="article-card" v-for="item in cards" @click="toArticle(item.id)">
        <img :src="item.pic" alt="" class="cover-image"/>
        <div class="card-content">
          <el-tooltip :content="item.title" placement="top">
            <div class="card-title">{{ item.title }}</div>
          </el-tooltip>
          <div class="article-type">
            <el-tag type="success">{{ showDictUtil(item.articleType, dict) }}</el-tag>
          </div>
          <span class="card-date">{{ parseTime(item.createTime, '{y}-{m}-{d}') }}</span>
          <span class="card-date" style="margin-right: 10px">作者：{{ item.user.nickName }}</span>
        </div>
        <div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {getArticlePages} from "@/api/articleApi.js"
import {parseTime} from "@/tool/utils.js"
import {getDict} from "@/api/common.js"
import {showDictUtil} from "@/tool/commonFun.js"

const router = useRouter()

// 响应式状态
const loading = reactive({
  tjLoad: true,
  sxLoad: true,
  cardsLoad: true
})

const page = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const cards = ref([])
const tjCards = ref([])
const dict = ref([])
const buts = ref([])
const activeBut = ref('')
const type = ref(null)

// 计算属性
const firstFourItems = computed(() => tjCards.value.slice(0, 4))
const remainingItems = computed(() => tjCards.value.slice(4))

// 方法
const handleSizeChange = () => fetchArticles()
const handleCurrentChange = () => fetchArticles()

const selectedBut = (value, index) => {
  page.currentPage = 1
  page.pageSize = 10
  activeBut.value = index
  type.value = value.value
  fetchArticles()
}

const toArticle = (id) => {
  router.push(`/health/article/${id}`)
}

// 数据获取
const fetchArticles = async (isVip = 0) => {
  const data = {
    articleType: type.value,
    isVip,
    status: '1',
    ...(isVip ? {} : {currentPage: page.currentPage, pageSize: page.pageSize})
  }

  try {
    const res = await getArticlePages(data)
    isVip ? (tjCards.value = res.data.articles) : (cards.value = res.data.articles)
    if (!isVip) page.total = res.data.total
  } finally {
    loading[isVip ? 'tjLoad' : 'cardsLoad'] = false
  }
}

const fetchDict = async () => {
  try {
    const res = await getDict({value: 'wz_lx'})
    dict.value = res.data[0].child
    buts.value = dict.value.map(item => ({
      label: item.label,
      value: item.value,
      checked: false
    }))
  } finally {
    loading.sxLoad = false
  }
}

const isTitleOverflow = (title) => {
  const el = document.createElement('span')
  el.style.visibility = 'hidden'
  el.style.whiteSpace = 'nowrap'
  el.textContent = title
  document.body.appendChild(el)
  const width = el.offsetWidth
  document.body.removeChild(el)
  return width > 250 // 根据实际容器宽度调整
}

// 生命周期
onMounted(async () => {
  await Promise.all([fetchArticles(), fetchArticles(1), fetchDict()])
})
</script>

<style scoped>
.home {
  margin: 0 auto;
  width: 85%;
}

.sx {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.sx-but {
  flex: 1;
  white-space: nowrap;
  overflow-x: auto;
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.article-card, .tj-small-article-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.article-card:hover, .tj-small-article-card:hover {
  transform: translateY(-5px);
  cursor: pointer;
}

.cover-image {
  width: 100%;
  height: 170px;
  object-fit: cover;
}

.card-content {
  padding: 12px;
}

.card-title {
  font-size: 15px;
  font-weight: 500;
  height: 3em;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.featured-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  min-height: 450px;
  margin-bottom: 2rem;
}

.featured-carousel {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.carousel-card {
  position: relative;
  height: 100%;
  cursor: pointer;
  transition: transform 0.3s;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.carousel-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 2rem;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  color: white;
}

.article-title {
  font-size: 1.5rem;
  margin: 0.5rem 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.9rem;
  opacity: 0.9;
}

.recommend-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
  padding: 0;
  margin: 0;
  list-style: none;
}

.recommend-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform0 .2s, box-shadow 0.2s;
}

.recommend-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.card-image {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

.card-content {
  padding: 1rem;
}

.card-title {
  font-size: 1rem;
  margin: 0 0 0.5rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 3em;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5rem;
}

.meta-info {
  display: flex;
  gap: 0.8rem;
  font-size: 0.85rem;
  color: #666;
}

@media (max-width: 1200px) {
  .featured-section {
    grid-template-columns: 1fr;
  }

  .featured-carousel {
    height: 350px;
  }
}

@media (max-width: 768px) {
  .article-title {
    font-size: 1.2rem;
  }

  .card-image {
    height: 120px;
  }
}

@media (hover: hover) {
  .carousel-card:hover .carousel-image {
    transform: scale(1.03);
  }
}
</style>